package com.gp.study.mybatis.handler;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;

import com.gp.study.mybatis.session.Configuration;


/**
 *  Statement 真正和数据库打交道的
 *  封装底层jdbc
 * @author USER
 *
 */
public class StateMentHandler {
	
	private ResultSetHandler resultSetHandler;
	private ParameterHandler parameterHandler;
	
	public StateMentHandler() {
		this.resultSetHandler = new ResultSetHandler();
		this.parameterHandler = new ParameterHandler();
	}

	public <T> T query(String statement, Object[] parameter, Class<?> pojo) throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
		// 处理参数， 赋值
		Connection conn = getConnection();
		PreparedStatement prepareStatement = conn.prepareStatement(statement);
		parameterHandler.handStatementParams(prepareStatement,parameter);
		//执行
		ResultSet rs = prepareStatement.executeQuery();
		//处理结果
		return (T)resultSetHandler.handResultSetPojo(rs,pojo);
	}

	private Connection getConnection() throws ClassNotFoundException, SQLException {
		ResourceBundle properties = Configuration.properties;
		String DRIVER_NAME = properties.getString("driver.name");
		String DB_URL = properties.getString("myql.url");
		String USER_NAME = properties.getString("mysql.username");
		String PASSWORD = properties.getString("mysql.password");
		Class.forName(DRIVER_NAME);
		return DriverManager.getConnection(DB_URL, USER_NAME, PASSWORD);
	}

}
